﻿using B.S.GridManager.Api.Read.Application.Command.LogicalGrid;
using B.S.GridManager.Api.Read.Dtos;
using B.S.GridManager.ErrorCode;
using B.S.GridManager.Infrastructure.Interface;
using B.S.GridManger.Domain.Entities;
using MediatR;
using System.Collections.Generic;

namespace B.S.GridManager.Api.Read.Application.CommandHandler.LogicalGrid
{
    /// <summary>
    /// 查询逻辑网格处理类
    /// </summary>
    public class GetLogicGridHandler : IRequestHandler<GetLogicGridCommand, ApiResult<List<LogialGridDTO>>>
    {
        private readonly IBaseRepository<LogicGridModel> logicalRepo;
        private readonly IBaseRepository<DepartmentModel> departRepo;

        /// <summary>
        /// 构造函数,注入仓储
        /// </summary>
        /// <param name="logicalRepo">逻辑网格仓储</param>
        /// <param name="departRepo">部门仓储</param>
        public GetLogicGridHandler(IBaseRepository<LogicGridModel> logicalRepo,IBaseRepository<DepartmentModel> departRepo)
        {
            this.logicalRepo = logicalRepo;
            this.departRepo = departRepo;
        }
        /// <summary>
        /// 查询逻辑网格处理方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<List<LogialGridDTO>>> Handle(GetLogicGridCommand request, CancellationToken cancellationToken)
        {

            ApiResult<List<LogialGridDTO>> result = new ApiResult<List<LogialGridDTO>>(); //实例化响应包装类

            var logicals = logicalRepo.GetAll().Where(x=>x.IsDeleted!=true);//所有逻辑网格表达式
            var logicalFather = logicalRepo.GetAll().Where(x => x.IsDeleted != true);//所有逻辑网格表达式
            var departs = departRepo.GetAll().Where(y=>y.IsDeleted!=true);//所有部门表达式

            //条件过滤
            if (!string.IsNullOrEmpty(request.LogicGridName)) { 
                logicals = logicals.Where(x=>x.LogicGridName.Contains(request.LogicGridName));  
            }

            if (request.ParentId!=0)
            {
                logicalFather = logicalFather.Where(x=>x.Id==request.ParentId);
            }

            var linq = from l in logicals
                       join f in logicalFather on l.ParentId equals f.Id
                       join d in departs on l.DepartmentId equals d.Id
                       select new LogialGridDTO
                       {
                           Id = l.Id,
                           DepartmentId = l.DepartmentId,
                           DepartmentName = d.DepartName,
                           LogicGridName = l.LogicGridName,
                           LogicGridCode = l.LogicGridCode,
                           ParentId = f.Id,
                           ParentLogicGridName = f.LogicGridName
                       };
            result.Data = linq.ToList();
            result.Code = ApiEnums.Success;
            result.Msg = "查询逻辑网格列表成功!";
            return Task.FromResult(result);
        }
    }
}
